﻿/*********************************************
 创建者：  george
 创建时间：2016-11-29
 功能说明：系统公用方法
 ********************************************/
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using com.nm.Helper;
using com.nm.library;
using com.nm.library.Helper;
using george.Data;
using NHibernateVertica;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Core.Objects;
using System.IO;
using System.Linq;
using System.Text;
using Vertica.Data.VerticaClient;
using george.Helper;
using BaseAPI.model;

namespace BaseAPI
{
    /// <summary>
    /// 公共接口
    /// </summary>
    public class CommonHandler : BaseHandler
    {

        private VerticaDataHelper VerticaHelper { get; set; } = new VerticaDataHelper();

        /// <summary>
        /// 获取指定表名,字段名最大值(限Int类型)
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="sortName"></param>
        /// <returns></returns>
        [MustLogin]
        [Description("获取排序值")]
        [ReturnType(typeof(int), "最大值")]
        public ApiResult GetSort([ParamDescription("表名")] string tableName,
            [ParamDescription("指定取值字段")] string sortName)
        {
            if (string.IsNullOrWhiteSpace(tableName) || string.IsNullOrWhiteSpace(sortName))
                return Error("参数不能为空");
            var dc = new SysEntities();
            var r = 0;
            var recordNumber = new ObjectParameter("m", System.Data.DbType.Int32);
            dc.sp_tableSort(tableName, sortName, recordNumber);
            r = (int)recordNumber.Value;
            return Success(r);
        }

        [MustLogin]
        [Description("系统日志")]
        [ReturnType(typeof(PaperData<SysLogList>))]
        public ApiResult GetLog([ParamDescription("开始时间")] DateTime BeginDate = default(DateTime),
            [ParamDescription("结束时间")] DateTime EndDate = default(DateTime),
            [ParamDescription("查询条件")] string Keys = "",
            [ParamDescription("页码")] string key = "",
            [ParamDescription("页码")] int Page = 1,
            [ParamDescription("页数")] int Size = 10)
        {
            if (EndDate == Convert.ToDateTime("0001/1/1 0:00:00"))
            {
                EndDate = DateTime.Now;
            }

            var dc = new SysEntities();
            var query = (from log in dc.sys_log
                         join user in dc.sys_users on log.Operator equals user.UserID
                         where log.CreateTime >= BeginDate
                         where log.CreateTime <= EndDate
                         where log.LogContent.Contains(Keys)
                         orderby log.CreateTime descending
                         select new { log, user.LoginAccount });
            var result = PaperData<SysLogList>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.log.CreateTime).Skip(result.Skip)
                .Take(result.Limt).Select(o => new SysLogList
                {
                    Action = o.log.Action,
                    CreateTime = o.log.CreateTime,
                    HostAddress = o.log.HostAddress,
                    ID = o.log.ID,
                    LogContent = o.log.LogContent,
                    Operator = o.LoginAccount
                }).ToList();
            return Success(result);
        }

        [MustAdmin]
        [Description("系统日志文件")]
        [ReturnType(typeof(IList<string>))]
        public ApiResult GetSysLogs()
        {
            var filepath = ConfigurationHelper.Get("sys-log", @"E:\filemanager\site\release\App_Data\Log\");
            var theFolder = new DirectoryInfo(filepath);
            var dirInfo = theFolder.GetFiles();
            var list = new List<string>();
            foreach (var nextFolder in dirInfo.OrderByDescending(t => t.CreationTime))
            {
                //var fileInfo = nextFolder.GetFiles();
                list.AddRange(new[] { nextFolder.Name });
            }
            return Success(list);
        }

        [MustAdmin]
        [Description("系统日志文本")]
        [ReturnType(typeof(string))]
        public ApiResult GetSysLogsText([ParamDescription("文件名")]string name)
        {
            var filepath = ConfigurationHelper.Get("sys-log", @"E:\filemanager\site\release\App_Data\Log\");
            var fs = File.Open(Path.Combine(filepath, name), FileMode.Open, FileAccess.Read);
            var bytes = new byte[fs.Length];
            fs.Read(bytes, 0, (int)fs.Length);
            fs.Close();
            return Success(Encoding.UTF8.GetString(bytes));
        }

        #region 下拉列表获取
        [MustLogin]
        [Description("获取大类")]
        [ReturnType(typeof(IList<DownListModel.KindInfo>))]
        public ApiResult GetKindInfo()
        {
            IList<DownListModel.KindInfo> result = null;
            string sql = $@"select DISTINCT KindID,KindName from nods.nods_erp_SD_Mat_Kind b where b.KindID in ( select DISTINCT KindID from ndw.ndw_KindToItem ) and ExtrSource = '{UserInfo.UserExtrSource}'";
            VerticaCommand command = new VerticaCommand(sql);
            var dt = VerticaHelper.ExecuteDataTable(command);
            result = ModelConvertHelper<DownListModel.KindInfo>.ConvertToModel(dt);
            return Success(result);
        }
        #endregion

        [MustLogin]
        [Description("获取性别")]
        [ReturnType(typeof(IList<DownListModel.SexInfo>))]
        public ApiResult GetSexInfo()
        {
            IList<DownListModel.SexInfo> result = null;
            string sql = $@"select DISTINCT SexID,SexName from nods.nods_erp_SD_Mat_Sex where ExtrSource = '{UserInfo.UserExtrSource}'";
            VerticaCommand command = new VerticaCommand(sql);
            var dt = VerticaHelper.ExecuteDataTable(command);
            result = ModelConvertHelper<DownListModel.SexInfo>.ConvertToModel(dt);
            return Success(result);
        }

        [MustLogin]
        [Description("获取小类")]
        [ReturnType(typeof(IList<DownListModel.ItemInfo>))]
        public ApiResult GetItemInfo([ParamDescription("大类联动")]string kindIds = "")
        {

            IList<DownListModel.ItemInfo> result = null;
            string sqlWhere = string.Empty;
            if (!string.IsNullOrEmpty(kindIds))
            {
                string temp_kindIds = kindIds.GetString();
                sqlWhere += $@"and KindID in {temp_kindIds}";
            }
            string sql = $@"select DISTINCT IsHome,ItemID,ItemorSub from ndw.ndw_KindToItem where ExtrSource = '{UserInfo.UserExtrSource}' and CompanyID = '{UserInfo.UserCompanyId}' {sqlWhere}";
            VerticaCommand command = new VerticaCommand(sql);
            var dt = VerticaHelper.ExecuteDataTable(command);
            result = ModelConvertHelper<DownListModel.ItemInfo>.ConvertToModel(dt);
            return Success(result);
        }

    }



    public class SysLogList
    {
        [ParamDescription("ID")]
        public int ID { get; set; }
        [ParamDescription("操作类型")]
        public int OperationType { get; set; }
        [ParamDescription("日志内容")]
        public string LogContent { get; set; }
        [ParamDescription("操作员")]
        public string Operator { get; set; }
        [ParamDescription("访问时间")]
        public DateTime? CreateTime { get; set; }
        [ParamDescription("IP地址")]
        public string HostAddress { get; set; }
        [ParamDescription("调用方法")]
        public string Action { get; set; }
    }
}
